package com.binguo.common.sms;


import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

/**
 */
//@Slf4j
public class HttpUtil {

    /*----- HTTP调用远程服务超时限制 ------*/
    //连接远程主机超时限制（单位：毫秒）
    public static final int HTTP_CONNECTION_TIMEOUT = 1000;
    //从主机读取数据超时（单位：毫秒）
    public static final int HTTP_READ_TIMEOUT = 3 * 1000;

    public static String sendGet(String url, String param) {
        return sendGet(url, param, HTTP_CONNECTION_TIMEOUT, HTTP_READ_TIMEOUT);
    }

    public static String sendGet(String url, String param, int timeOut) {
        return sendGet(url, param, timeOut, timeOut);
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, int connectionTimeOut, int readTimeOut) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
//            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
//            connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//            connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
//            connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Vary", "Accept-Encoding");
            connection.setRequestProperty("Content-Language", "zh-CN");
            connection.setRequestProperty("Pragma", "no-cache");
            connection.setRequestProperty("Server", "DPweb");
//            connection.setRequestProperty("Cookie", "navCtgScroll=200; showNav=#nav-tab|0|0; showNav=#nav-tab|0|1; navCtgScroll=121; _hc.v=\"\\\"3e0a8f60-7f17-4287-a0c0-980351be98df.1426730853\\\"\"; abtest=\"52,133\\|47,122\\|44,106\"; _intcst=a; __utma=1.1108807772.1427022968.1427022968.1427022968.1; __utmc=1; __utmz=1.1427022968.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); PHOENIX_ID=0a0166ae-14c41989db3-21ff75; s_ViewType=10; JSESSIONID=FA1D5E0CA3CA34F37FB5C168C720D65C; aburl=1; cy=6; cye=suzhou");
            connection.setRequestProperty("User-Agent:", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36");
            connection.setRequestProperty("Host", "www.dianping.com");
//            connection.setRequestProperty("Transfer-Encoding", "chunked");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), Charset.forName("UTF-8")));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
//            log.error("发送GET请求出现异常！" + e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
//                log.error("close exception", e2);
            }
        }
        return result;
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @return URL 所代表远程资源的响应结果
     */
    public static String send(String url, String contentType, String authorization) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("Content-Type", contentType);
            connection.setRequestProperty("Authorization", authorization);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), Charset.forName("UTF-8")));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
//                log.error("close exception", e2);
            }
        }
        return result;
    }


    public static String sendPost2(String url, String contentType, String authorization) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Authorization", authorization);
            conn.setConnectTimeout(100000);
            conn.setReadTimeout(100000);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print("");
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
//                log.error("IO exception", ex);
            }
        }
        return result;
    }

    public static String sendJSONPost(String url, String param) {
        return sendPost(url, param, "application/json", "application/json");
    }

    public static String sendJSONPost(String url, String param, int timeOut) {
        return sendPost(url, param, "application/json", "application/json", timeOut, timeOut);
    }

    public static String sendPost(String url, String param) {
        return sendPost(url, param, "*/*", "*/*");
    }

    public static String sendPost(String url, Object param) {

        return sendPost(url, param, "*/*", "*/*", HTTP_CONNECTION_TIMEOUT,
                HTTP_READ_TIMEOUT);
    }

    public static String sendPost(String url, String param, String accept, String contentType) {
        return sendPost(url, param, accept, contentType, HTTP_CONNECTION_TIMEOUT,
                HTTP_READ_TIMEOUT);

    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, String accept, String contentType, int connectionTimeOut, int readTimeOut) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", accept);
            conn.setRequestProperty("content-type", contentType);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,ja;q=0.4,zh-TW;q=0.2");
            conn.setConnectTimeout(connectionTimeOut);
            conn.setReadTimeout(readTimeOut);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
//            log.error("发送 POST 请求出现异常！" + e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
//                log.error("IO exception", ex);
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, Object param, String accept, String contentType, int connectionTimeOut, int readTimeOut) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", accept);
            conn.setRequestProperty("content-type", contentType);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setConnectTimeout(connectionTimeOut);
            conn.setReadTimeout(readTimeOut);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
//            log.error("发送 POST 请求出现异常！" + e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
//                log.error("IO exception", ex);
            }
        }
        return result;
    }

    public static void downloadNet(String imgUrl, String filename) {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        try {
            URL url = new URL(imgUrl);
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(new File(filename));

            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception{
        String s = "Good  morning！";

        String aa = "我想听周杰伦的告白的气球";
        String bb = "周杰伦";

        String cc = aa.substring(aa.indexOf(bb) + bb.length());
        System.out.println(cc);

        System.out.println(cc.substring(cc.indexOf("的") + 1));
//        String sa = new String((Base64.Encoder.class).encode(s.getBytes())).replaceAll("\\+","").replaceAll(" ", "");

        System.out.println(System.currentTimeMillis());
//        System.out.println("SeKAmW0gbWVudG8gIQ==".equals(sa));
//        System.out.println(sa);
        System.out.println("".length());
//        HttpUtil.downloadNet("http://7teawj.com1.z0.glb.clouddn.com/Fla0_TkWD4icG4hc-d5VZqRhMaqR", "d:/aa.png");
    }


    public static String getVoiceBox(String aaa){

        try {
            URL url = new URL(aaa);
            URLConnection conn = url.openConnection();
            conn.setConnectTimeout(200000);
            conn.setReadTimeout(200000);
            conn.connect();

            InputStream is = null;

            FileOutputStream fos = null;
            try {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String line;
                String result = "";
                while ((line = in.readLine()) != null) {
                    result += line;
                }

                return result;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                try {
                    if (is != null){
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    if (fos != null){
                        fos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }


        }catch (Exception e){

        }

        return null;
    }
}
